package com.community.web.master.handler;

import com.community.common.result.Result;
import com.community.web.master.constant.MessageConstant;
import com.community.web.master.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕获业务异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(BaseException.class)
    public Result exceptionHandler(BaseException e) {
        log.error("异常信息：{}", e.getMessage());
        return Result.error(e.getMessage());
//        return Result.success();
    }

    /**
     * 处理sql异常
     *
     * @param ex
     * @return
     */

    @ExceptionHandler
    public Result exceptionHandler(java.sql.SQLIntegrityConstraintViolationException ex) {
//        Duplicate entry 'zhangsan' for key 'employee.idx_username'
        String message = ex.getMessage();
        //用户名重复
        if (message.contains("Duplicate entry")) {
            String[] split = message.split(" ");
            String username = split[2];
            String msg = username + MessageConstant.ALREADY_EXISTS;
            return Result.error(msg);
        }
        else return Result.error(MessageConstant.ERROR);


    }
}
